package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.config.GlobalConfig;
import com.cpit.platform.config.UploadPathConfig;
import com.cpit.platform.log.LogOperator;
import com.cpit.qualitycontrol.dao.ApkUploadRepository;
import com.cpit.qualitycontrol.entity.ApkUpload;
import com.cpit.qualitycontrol.service.ApkUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
@Transactional
public class ApkUploadServiceImp implements ApkUploadService {

    private static final String loggerName = ApkUploadServiceImp.class.getName();

    @Autowired
    private UploadPathConfig uploadPath;

    @Autowired
    private GlobalConfig globalConfig;

    @Autowired
    ApkUploadRepository apkUploadRepository;

    @Override
    public ApkUpload versionRelease(ApkUpload apkUpload) {
        apkUpload.setFilepath(handleImage(apkUpload.getFilepath()));
        return apkUploadRepository.save(apkUpload);
    }

    // 处理图片
    private String handleImage(String apkpath) {
        if (StringUtils.isEmpty(apkpath)) {
            return null;
        }
        StringBuilder imgSB = new StringBuilder();
        if (apkpath.indexOf(uploadPath.getTemp()) >= 0) {
            String fileName = apkpath.substring(apkpath.lastIndexOf("/") + 1);
            Path sourcePath = Paths.get(apkpath);
            Path targetPath = Paths.get(uploadPath.getApk(), fileName);
            try {
                // 判断目录是否存在
                File apkFile = new File(uploadPath.getApk());
                if (!apkFile.exists() && !apkFile.isDirectory()) {
                    apkFile.mkdirs();
                }

                Files.move(sourcePath, targetPath);
                if ("/".equals(globalConfig.getContextPath())) {
                    imgSB.append("file/app/download/apk/").append(fileName).append(",");
                } else {
                    imgSB.append(globalConfig.getContextPath()).append("/file/app/download/apk/")
                            .append(fileName).append(",");
                }
            } catch (IOException e) {
                LogOperator.err(loggerName, "file move error!", e);
            }
        }
        if (imgSB.length() > 0) {
            return imgSB.substring(0, imgSB.length() - 1);
        } else {
            return null;
        }
    }

    @Override
    public ApkUpload queryLatestVersion() {
        return apkUploadRepository.queryLatestVersion();
    }
}
